package com.coding.service.impl;

import com.coding.base.pojo.BaseModel;
import com.coding.base.util.DateUtil;
import com.coding.base.util.PoemUtil;
import com.coding.dao.UserDao;
import com.coding.dao.WrongDao;
import com.coding.pojo.Poem;
import com.coding.pojo.User;
import com.coding.pojo.Wrong;
import com.coding.service.WrongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther wangchenghao
 * @date 2020/8/15
 **/
@Service
public class WrongImpl implements WrongService {
    @Autowired
    WrongDao wrongDao;
    @Autowired
    UserDao userDao;

    @Override
    public void selectUserWrong(int user_id, BaseModel baseModel) throws Exception {
        User user = userDao.getuserbyuser_id(user_id);
        if (user == null) {
            baseModel.setFailure("该用户不存在，请检查账号是否正确");
            return;
        }
        List<Wrong> wrongList = wrongDao.selectByUser(user_id);
        List<Poem> poemList = new ArrayList<>();
        for (Wrong wrong : wrongList
        ) {
            poemList.add(wrong.getPoem());
        }
        poemList = PoemUtil.setText(poemList);
        for (int i = 0; i < poemList.size(); i++) {
            wrongList.get(i).setPoem(poemList.get(i));
        }
        if (wrongList != null) {
            baseModel.setSucceed("成功获得错题", wrongList);
        } else {
            baseModel.setFailure("获得错题失败");
        }

    }

    @Override
    public void addWrongPoem(int user_id, int source_id, BaseModel baseModel) throws Exception {
        User user = userDao.getuserbyuser_id(user_id);
        if (user == null) {
            baseModel.setFailure("该用户不存在，请检查账号是否正确");
            return;
        }
        Wrong wrong = wrongDao.selectWrong(user_id, source_id, "poem");
        if (wrong != null) {
            baseModel.setFailure("用户已添加错题");
            return;
        }
        Wrong newWrong = new Wrong();
        newWrong.setUser_id(user_id);
        newWrong.setSource_id(source_id);
        newWrong.setWrong_time(DateUtil.getStringDate());
        if (wrongDao.insertSelective(newWrong) == 1) {
            baseModel.setSucceed("新增诗词错题成功", newWrong);
        } else {
            baseModel.setFailure("新增诗词错题失败");
        }
    }
}
